import {
	trace_create
} from "@/common/api/index.js";

module.exports = {
	data() {
		return {
			addressInfo: {
				longitude: "", // 经度
				latitude: "", // 维度
				address: "", // 位置信息描述
			},
		};
	},
	onLoad() {},
	created() {},
	mounted() {},
	onHide() {},
	methods: {
		openLocation() {
			let that = this;
			return new Promise(async (resolve, reject) => {
				uni.startLocationUpdate({
					success: async (res) => {
						console.log(1111);
						await that.getLocationUpload();
						resolve();
					},
					fail: (err) => console.error("开启应用接收位置消息失败：", err),
					complete: (msg) => console.log("调用开启应用接收位置消息 API 完成"),
				});
			});
		},
		getLocationUpload() {
			let that = this;
			return new Promise((resolve, reject) => {
				console.log(4444);
				uni.getLocation({
					type: "gcj02",
					geocode: true,
					success: async (res) => {
						console.log(2222);
						console.log(res, "that.addressInfo.latitude = res.latitude;");
						that.addressInfo.latitude = res.latitude;
						that.addressInfo.longitude = res.longitude;
						that.addressInfo.address =
							`${res.address.province}${res.address.city}${res.address.district}${res.address.street}${res.address.streetNum}${res.address.poiName}`;
						await that.set_trace_create();
						resolve(res);
					},
					fail: (err) => {
						console.log(5555, err);
						reject(err);
					},
				});
			});
		},
		onListenerLocation() {
			let that = this;
			uni.onLocationChange(async (callback) => {
				if (
					callback.latitude != that.addressInfo.latitude ||
					callback.longitude != that.addressInfo.longitude
				) {
					let dist = that.calculateDistance(callback, that.addressInfo, {
						units: "meters",
					});
					if (dist > 50) {
						console.log("callback=>", callback);
						console.log("that.addressInfo=>", that.addressInfo);

						await that.getLocationUpload();
						// that.addressInfo.latitude = callback.latitude;
						// that.addressInfo.longitude = callback.longitude;
					}
				}
			});
		},
		async set_trace_create() {
			console.log(3333);
			let res = await trace_create({
				...this.addressInfo,
			});
			if (res.code == 1) {
				console.log(res);
			} else {
				// this.showMsg(res.msg);
			}
		},
		calculateDistance(pta, ptb, options) {
			const R = 6371000; // 地球半径，单位：米
			const lat1 = this.deg2rad(pta.latitude);
			const lat2 = this.deg2rad(ptb.latitude);
			const dLat = this.deg2rad(ptb.latitude - pta.latitude);
			const dLon = this.deg2rad(ptb.longitude - pta.longitude);

			const a =
				Math.sin(dLat / 2) * Math.sin(dLat / 2) +
				Math.cos(lat1) *
				Math.cos(lat2) *
				Math.sin(dLon / 2) *
				Math.sin(dLon / 2);
			const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			return R * c;
		},
		deg2rad(deg) {
			return deg * (Math.PI / 180);
		},
	},
};